<template>
<div class="main_box">
  <el-row>
    <el-col :span="12">
      <Crumbs></Crumbs>
    </el-col>
    <el-col :span="12">
      <div class="opration_wrap">
        <el-button type="primary" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
    </el-col>
  </el-row>
  <div class="add_wrap">
    <div class="tit">
      <h2>基础信息</h2>
    </div>
    <el-form :model="editForm" ref="editForm" label-width="200px" :rules="roleRules">
      <el-row>
        <el-form-item label="头像" class="img_item" prop="imageUrl">
          <div class="img photo">
            <img :src="editForm.imageUrl" v-if="editForm.imageUrl"/>
            <i class="el-icon-plus" v-if="!editForm.imageUrl"></i>
          </div>
          <div class="txt photo_txt">
            <span>图片请小于5M（jpg、png、bmp）</span>
          </div>
          <el-input type="file" @change="handleFile('hiddenfile','imageUrl')" id="hiddenfile" class="file photo_input"></el-input>
        </el-form-item>
        <el-form-item label="客户编号：" prop="customerCode">
          <span>{{editForm.customerCode}}</span>
        </el-form-item>
        <el-form-item label="昵称：" prop="customerNickName">
          <el-input v-model="editForm.customerNickName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" prop="tel">
          <span>{{editForm.tel}}</span>
        </el-form-item>
        <el-form-item label="客户类型：" prop="customerFlag">
          <span v-if="editForm.customerFlag == 1">APP客户</span>
          <span v-if="editForm.customerFlag == 2">代理客户</span>
          <span v-if="editForm.customerFlag == 3">系统客户</span>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option key="1" label="男" value="1"></el-option>
            <el-option key="2" label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月：" prop="birthday">
          <el-date-picker v-model="editForm.birthday" type="date" placeholder="请选择日期" :clearable="true"></el-date-picker>
        </el-form-item>
        <el-form-item label="地区：" prop="areaIds">
          <ProvinceCity :provinceCityValues="editForm.areaIds" @provinceCityChange="handleItemChange"></ProvinceCity>
        </el-form-item>
        <el-form-item label="客户积分：" prop="customerPoint">
          <span>{{editForm.customerPoint}}</span>
        </el-form-item>
        <el-form-item label="客户等级：" prop="customerRank">
          <span>{{editForm.customerRank}}</span>
        </el-form-item>
        <el-form-item label="客户经验：" prop="customerExperience">
          <span>{{editForm.customerExperience}}</span>
        </el-form-item>
        <el-form-item label="关注数：" prop="followsCount">
          <span>{{editForm.followsCount}}</span>
        </el-form-item>
        <el-form-item label="粉丝数：" prop="fansCount">
          <span>{{editForm.fansCount}}</span>
        </el-form-item>
        <el-form-item label="简介：" prop="userIntroduce">
          <el-input type="textarea" v-model="editForm.userIntroduce"></el-input>
        </el-form-item>
        <el-form-item label="推荐人昵称：" prop="inviterCustomerNickName">
          <span>{{editForm.inviterCustomerNickName}}</span>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button type="primary" @click="sureClick">保 存</el-button>
          <el-button @click="returnList">取 消</el-button>
        </el-form-item>
      </el-row>
      </el-form>
  </div>
 </div>
</template>

<script>
import * as validators from "@/utils/validators";
import * as message from "@/constants/message";
import Crumbs from "@/components/Crumbs";
import ProvinceCity from "@/components/ProvinceCity";
export default{
  data(){
      return {
         editForm: {
           imageUrl: "",
           customerCode: "",
           customerNickName: "",
           tel: "",
           customerFlag: "",
           sex: "",
           birthday: "",
           areaIds: [],
           customerPoint: "",
           customerRank: "",
           customerExperience: "",
           followsCount : "",
           fansCount: "",
           userIntroduce: "",
           inviterCustomerNickName: "",
           provinceId: "",
           cityId: "",
        },
        roleRules: {
          imageUrl:[
            { required: true, message: "请选择头像", trigger: "change" }
          ],
          birthday: [
            { required: true, message: "请选择出生年月", trigger: "change" }
          ],
          customerNickName: [
            { required: true, message: "请输入昵称", trigger: "blur" }
          ],
          areaIds: [
            { required: true, message: "请选择所在地区", trigger: "change" }
          ],
          sex: [
            { required: true, message: "请选择性别", trigger: "change" }
          ],
          userIntroduce:[
            { required: true, message: "请输入简介", trigger: "blur" }
          ]
        }
      }
  },
  components: {
    Crumbs,
    ProvinceCity
  },
  methods: {
    init(){
      this.getData();
    },
    handleItemChange(val){
      this.editForm.areaIds = [val.provinceId,val.cityId]
    },
    handleFile(id,data){
      const $target = document.getElementById(id);
      const _this = this;
      const file = $target.files[0];
      if (!this.beforeAvatarUpload(file)) {
        return
      }
      this.$Get('/aliyun/sts/token')
      .then((res) => {
        let OSS = require('ali-oss');
      let client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: res.data.accessKeyId,
        accessKeySecret: res.data.accessKeySecret,
        stsToken: res.data.securityToken,
        bucket: _this.$Config.oss.bucket
      })
      const fileName = file.name;
      console.log(fileName)
        const fileType = fileName.split("\.")[1];
        let fileTempName = new Date().getTime() + fileName.split("\.")[0];
        if (fileTempName.length > 5){
          fileTempName = fileTempName.substring(0,12);
        }
        const newName = fileTempName +"."+ fileType;
      const storeAs = "web_images/Customer/" + newName;
      const resultUpload = "";
      client.put(storeAs, file,{})
        .then(function (r1) {
          let realUrl = r1.url.replace("cactus-pro.oss-cn-hangzhou.aliyuncs.com","image.vvhuimei.com");
          _this.editForm[data] = realUrl;
        }).catch(function (err) {
        console.error( err);
      });
    })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isPNG && !isBMP) {
        this.$message.error('上传图片只能是 JPG , PNG , BMP 格式!');
      }

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return (isJPG || isPNG || isBMP) && isLt2M ;
    },
    getData(){
      this.$Get(this.$Config.api.customer, {customerId:this.$route.query.id})
      .then(res => {
        this.$Utils.bindingBean(this.editForm, res.data);
        this.editForm.areaIds = [this.editForm.provinceId, this.editForm.cityId];
      })
    },
    sureClick() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
          .then(() => {
            this.editData();
          });
        }
      })
    },
    editData() {
      let data = {
        customerId: this.$route.query.id,
        imageUrl: this.editForm.imageUrl,
        customerNickName: this.editForm.customerNickName,
        areaIds: this.editForm.areaIds,
        sex: this.editForm.sex,
        birthday: this.editForm.birthday,
        userIntroduce: this.editForm.userIntroduce,
        loginName: this.editForm.loginName
      };
      this.submitData(data)
    },
    submitData(data){
      this.$Put(this.$Config.api.customer, data)
      .then(res => {
        console.log(res)
        this.$notify.success({
          title: message.TITLE_SUCCESS,
          message: message.MSG_ACTION_SUCCESS
        });
        this.returnList(data);
      })
      .catch(error => {
          if (error.msg) {
          this.$notify.error({
            title: message.TITLE_ERROR,
            message: error.msg
          });
        }
      })
    },
    returnList(data){
      this.$router.push({name: "客户列表", params:data})
    }
  },
  mounted(){
    this.init();
  }
}
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope>
</style>
